package control;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.PrintJob;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import view.Gui;
import xl.XLException;

class PrintMenuItem extends JMenuItem implements ActionListener {
    private Gui gui;

    public PrintMenuItem(Gui gui) {
        super("Print");
        this.gui = gui;
        addActionListener(this);
    }

    public void actionPerformed(ActionEvent event) {
        Toolkit toolkit = gui.getToolkit();
        PrintJob printJob = toolkit.getPrintJob(gui, "Frame", null);
        if (printJob == null) {
            throw new XLException("PrintJob failed");
        }
        Graphics graphics = printJob.getGraphics();
        Dimension size = gui.getSize();
        Dimension pageSize = printJob.getPageDimension();
        graphics.translate((pageSize.width - size.width) / 2,
                (pageSize.height - size.height) / 2);
        graphics.drawRect(-1, -1, size.width + 1, size.height + 1);
        gui.printAll(graphics);
        graphics.dispose();
        printJob.end();
    }
}